package com.sinoglobal.ningxia.activity.vip;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.beans.AdverVo;
import com.sinoglobal.ningxia.beans.VersionVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.StringUtil;
import com.sinoglobal.ningxia.version.VersionUitls;
import com.sinoglobal.ningxia.version.VersionUpgradeActivity;

import net.tsz.afinal.FinalBitmap;

/**
 * @title: AboutActivity.java
 * @package com.sinoglobal.ningxia.activity.vip
 * @description: 关于页面
 * @author lms
 * @date 2014-6-19 下午6:15:16
 */
public class About extends BaseActivity implements OnClickListener {
	// 检查新版本
	private Button checkVersion;
	// 分享
	private Button share;
	// 对话框
	private Dialog messageDialog;
	// 广告位,广告位的关闭按钮
	private ImageView adverImg, closeAdver;
	// 广告信息的bean
	private AdverVo adverVo;
	// 版本号
	private TextView version;
	ItktAsyncTaskWithDialog<Void, Void, VersionVo> task;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vip_about);
		openChenJInShi();//开启沉浸式
		init();
		setListener();
		downLoadAdver();
	}

	private void setListener() {
		// 检查版本更新
		checkVersion.setOnClickListener(this);
		// 分享
		share.setOnClickListener(this);
		// 广告位的点击事件
		adverImg.setOnClickListener(this);
		// 关闭广告位
		closeAdver.setOnClickListener(this);
	}

	// 检查版本是否需要更新
	protected void checkNewVersion() {
		task = new ItktAsyncTaskWithDialog<Void, Void, VersionVo>(getResources().getString(R.string.searching_infor), true, true) {

			@Override
			public VersionVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getVersionInfo();
			}

			@Override
			public void after(VersionVo result) {
				// 数据为空，显示reLoad
				if (null == result) {
					showReLoading();
					return;
				}

				// 判断返回的是否需要更新的code值
				if (Code.CODE_SUCCESS != result.getCode()) {
					showShortToastMessage(result.getMessage());
					return;
				}

				// 新版本号大于当前版本号时，弹出更新对话框
				if (!StringUtil.equals(String.valueOf(result.getNew_banben()), VersionUitls.getVersionName(FlyApplication.context))) {
					SharedPreferenceUtil.saveString(FlyApplication.context, "versionUrl", result.getUrl());
					try {
						showDialog(result);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					showConfirmDialog();
				}

			}

			@Override
			public void exception() {
				showShortToastMessage(getResources().getString(R.string.loadFail));
			    task.cancel(true);
			}
		};
		task.execute();
	}

	@Override
	protected void onDestroy() {
		cancelTask(task);
		super.onDestroy();

	}

	// 初始化view
	private void init() {
		int width = FlyApplication.widthPixels;
		titleView.setText(R.string.about);
		checkVersion = (Button) findViewById(R.id.check_version_btn);
		share = (Button) findViewById(R.id.share_btn);
		adverImg = (ImageView) findViewById(R.id.advertising);
		version = (TextView) findViewById(R.id.version_text);
		version.setText("V " + EquipmentUtil.getVersionCode(About.this).get("VersionName"));
		RelativeLayout.LayoutParams params = (LayoutParams) adverImg.getLayoutParams();
		params.height = width * 43 / 320;
		adverImg.setLayoutParams(params);
		closeAdver = (ImageView) findViewById(R.id.close_advertising);
	}

	// 提示已经是最新版本的对话框
	public void showConfirmDialog() {
		if (messageDialog != null) {
			messageDialog.dismiss();
			messageDialog = null;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.about_version_dialog, null);
		Button confirm = (Button) view.findViewById(R.id.confirm_btn);
		builder.setView(view);
		builder.setCancelable(true);
		confirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				messageDialog.dismiss();
			}
		});
		messageDialog = builder.create();
		messageDialog.show();
	}

	// 弹窗提示更新
	private void showDialog(final VersionVo version) {
		AlertDialog.Builder builder = new Builder(About.this);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle(getResources().getString(R.string.update_to) + version.getNew_banben());
		builder.setMessage(version.getGengxin());
		Log.i("dd", version.getGengxin());
		builder.setCancelable(false);
		builder.setNegativeButton(getResources().getString(R.string.update), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (!version.getUrl().contains(".apk")) {
					showShortToastMessage(getResources().getString(R.string.addr_error));
					return;
				}
				// 跳转到下载更新
				Intent intent = new Intent(About.this, VersionUpgradeActivity.class);
				intent.putExtra(VersionUpgradeActivity.DOWNLOAD, version.getUrl());
				FlyUtil.intentForward(About.this, intent);
			}
		});
		builder.setPositiveButton(getResources().getString(R.string.btn_cancle), null);
		builder.show();
	}

	// 加载广告信息
	private void downLoadAdver() {
		adverVo = new AdverVo();
		new ItktAsyncTaskWithDialog<Void, Void, AdverVo>(MContants.EMPTY_STRING, false, true) {

			@Override
			public AdverVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().downLoadAdver();
			}

			@Override
			public void after(AdverVo result) {
				// 数据为空
				if (null == result) {
					return;
				}

				// 判断返回的code值是否正确
				if (Code.CODE_SUCCESS != result.getCode()) {
					return;
				}
				adverVo.setAd_img(result.getAd_img());
				adverVo.setAd_url(result.getAd_url());
				String url = ConnectionUtil.localUrl + adverVo.getAd_img();
				ItktLog.i("--------ad   url-------->>>>>>>>>>>>" + url);

				// 获取图片地址为空时，显示默认图片
				if (MContants.EMPTY_STRING.equals(adverVo.getAd_img())) {
					adverImg.setVisibility(View.GONE);
				} else {
					adverImg.setVisibility(View.VISIBLE);
					FinalBitmap fb = FinalBitmap.create(FlyApplication.context);
					fb.display(adverImg, url);
					closeAdver.setVisibility(View.VISIBLE);
				}
				setShareData("ad_name", result.getAd_name());
				setShareData("ad_img", result.getAd_img());
				setShareData("ad_url", result.getAd_url());
			}

			@Override
			public void exception() {
			}
		}.execute();
	}

	// 设置share存储的数据
	private void setShareData(String key, String content) {
		SharedPreferenceUtil.saveString(FlyApplication.context, key, content);
	}

	// 判断是否连接网络
	public boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.check_version_btn:// 检查版本更新
			// 在联网情况下进行版本检测
			if (!isNetworkConnected(FlyApplication.context)) {
				showShortToastMessage(getResources().getString(R.string.no_connections));
				return;
			}
			checkNewVersion();
			break;
		case R.id.share_btn:// 分享
			FlyUtil.intentForward(About.this, QuickMark.class);
			break;
		case R.id.advertising:// // 广告位的点击事件
			if (!isNetworkConnected(FlyApplication.context)) {
				showShortToastMessage(getResources().getString(R.string.no_connections));
				return;
			}
			// 打开默认浏览器显示网页信息

			try {
				Uri uri = Uri.parse(adverVo.getAd_url());
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.close_advertising:// 关闭广告位
			adverImg.setVisibility(View.GONE);
			closeAdver.setVisibility(View.GONE);
			break;
		}
	}
}
